<template>
    <div class="chat-container">
      <!-- 顶部导航栏 -->
      <div class="chat-header">
        <img 
          :src="sellerAvatar" 
          class="user-avatar"
          @error="handleAvatarError"
        />
        <div class="user-info">
          <div class="user-name">{{ sellerInfo?.nickname || '未知用户' }}</div>
          <div class="online-status">{{ onlineStatus }}</div>
        </div>
      </div>
  
      <!-- 聊天内容区域 -->
      <div class="chat-messages" ref="messagesContainer">
        <div 
          v-for="(msg, index) in messages" 
          :key="index"
          :class="['message-wrap', msg.senderId === currentUser?.userId ? 'right' : 'left']"
        >
          <img 
            v-if="msg.senderId !== currentUser?.userId"
            :src="sellerAvatar"
            class="avatar"
            @error="handleAvatarError"
          />
          <div class="message-content">
            <div class="message-bubble">
              {{ msg.content }}
              <div class="message-time">{{ formatTime(msg.timestamp) }}</div>
            </div>
          </div>
          <img 
            v-if="msg.senderId === currentUser?.userId"
            :src="userAvatar"
            class="avatar"
            @error="handleAvatarError"
          />
        </div>
      </div>
  
      <!-- 输入区域 -->
      <div class="input-area">
        <el-input
          v-model="newMessage"
          placeholder="输入消息..."
          class="input-box"
          @keyup.enter.native="sendMessage"
          clearable
        >
          <template #append>
            <el-button 
              type="primary" 
              @click="sendMessage"
              class="send-btn"
              :disabled="!newMessage.trim()"
            >
              发送
            </el-button>
          </template>
        </el-input>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted, nextTick, computed } from 'vue'
  import { useRoute } from 'vue-router'
  import { Client } from '@stomp/stompjs'
  // 在 script setup 顶部添加导入
import SockJS from 'sockjs-client'
  const route = useRoute()
  const messagesContainer = ref(null)
  const currentUser = ref(null)
  const sellerInfo = ref(null)
  const messages = ref([])
  const newMessage = ref('')
  const stompClient = ref(null)
  
  const sellerAvatar = computed(() => {
  return `http://localhost:8092${sellerInfo.value?.avatar}`
})

const userAvatar = computed(() => {
  return `http://localhost:8092${currentUser.value?.avatar}`
})
  
  const onlineStatus = computed(() => {
    return sellerInfo.value?.loginStatus === '1' ? '在线' : '离线'
  })
  
  // 获取当前用户信息
  const fetchCurrentUser = async () => {
    try {
      const res = await fetch('http://localhost:8092/user/getUserDetails', {
        headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
      })
      const { code, data } = await res.json()
      if (code === 200) currentUser.value = data
    } catch (error) {
      console.error('获取用户信息失败:', error)
    }
  }
  
  // 获取卖家信息
  const fetchSellerInfo = async () => {
    try {
      const res = await fetch(
        `http://localhost:8092/user/getUserDetailById?userId=${route.query.sellerId}`
      )
      const { code, data } = await res.json()
      if (code === 200 && data.length > 0) sellerInfo.value = data
    } catch (error) {
      console.error('获取卖家信息失败:', error)
    }
  }
  
  const initWebSocket = () => {
  const token = localStorage.getItem('token')
  
  const client = new Client({
    brokerURL: 'ws://localhost:8092/ws-chat',
    connectHeaders: { 
      Authorization: `Bearer ${token}`,
      'X-Requested-With': 'XMLHttpRequest'  
    },
    webSocketFactory: () => {
      return new SockJS('http://localhost:8092/ws-chat', null, {
        transports: ['websocket', 'xhr-streaming'],
        withCredentials: true  // 必须与后端配置一致
      })
    },
    debug: (str) => console.debug('STOMP:', str),
    reconnectDelay: 5000,
    heartbeatIncoming: 4000,
    heartbeatOutgoing: 4000
  })

  client.onConnect = () => {
    client.subscribe(`/user/queue/chat`, message => {
      messages.value.push(JSON.parse(message.body))
      scrollToBottom()
    })
  }

  client.onStompError = (frame) => {
    console.error('WebSocket连接错误:', frame.headers.message)
  }

  client.activate()
  stompClient.value = client
}
  // 加载历史消息
  const loadHistory = async () => {
    try {
      const res = await fetch(
        `http://localhost:8092/chat/history?productId=${route.query.productId}`,
        { headers: { Authorization: `Bearer ${localStorage.getItem('token')}` } }
      )
      const { code, data } = await res.json()
      if (code === 200) messages.value = data
    } catch (error) {
      console.error('加载历史失败:', error)
    } finally {
      scrollToBottom()
    }
  }
  
  // 发送消息
  const sendMessage = () => {
    if (!newMessage.value.trim()) return
  
    const message = {
      receiverId: route.query.sellerId,
      productId: route.query.productId,
      content: newMessage.value.trim()
    }
    
    stompClient.value.publish({
      destination: '/app/send',
      body: JSON.stringify(message)
    })
    
    newMessage.value = ''
  }
  
  // 时间格式化
  const formatTime = timestamp => {
    try {
      const date = new Date(timestamp)
      return date.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
      })
    } catch {
      return '--:--'
    }
  }
  
  // 滚动到底部
  const scrollToBottom = () => {
    nextTick(() => {
      if (messagesContainer.value) {
        messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
      }
    })
  }
  
  
  onMounted(async () => {
    await fetchCurrentUser()
    await fetchSellerInfo()
    initWebSocket()
    loadHistory()
  })
  </script>
  
  <style scoped>
  .chat-container {
    display: flex;
    flex-direction: column;
    height: 100vh;
    background: #f5f5f5;
  }
  
  .chat-header {
    display: flex;
    align-items: center;
    padding: 12px 16px;
    background: #fff;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    z-index: 1;
  }
  
  .user-avatar {
    width: 40px;
    height: 40px;
    border-radius: 6px;
    margin-right: 12px;
    object-fit: cover;
  }
  
  .user-info {
    flex: 1;
  }
  
  .user-name {
    font-weight: 500;
    font-size: 16px;
    color: #333;
  }
  
  .online-status {
    font-size: 12px;
    color: #666;
  }
  
  .chat-messages {
    flex: 1;
    padding: 16px;
    overflow-y: auto;
    background: #f0f0f0;
  }
  
  .message-wrap {
    display: flex;
    margin: 12px 0;
    max-width: 75%;
    transition: all 0.3s ease;
    
    &.left {
      flex-direction: row;
      margin-right: auto;
      
      .message-bubble {
        background: #fff;
        border-radius: 0 12px 12px 12px;
      }
    }
    
    &.right {
      flex-direction: row-reverse;
      margin-left: auto;
      
      .message-bubble {
        background: #95ec69;
        border-radius: 12px 0 12px 12px;
      }
    }
  }
  
  .avatar {
    width: 36px;
    height: 36px;
    border-radius: 6px;
    margin: 0 8px;
    align-self: flex-end;
    object-fit: cover;
  }
  
  .message-bubble {
    padding: 10px 14px;
    line-height: 1.5;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    max-width: 400px;
    word-break: break-word;
    position: relative;
  }
  
  .message-time {
    font-size: 12px;
    color: #666;
    margin-top: 6px;
    text-align: right;
  }
  
  .input-area {
    padding: 16px;
    background: #fff;
    border-top: 1px solid #e8e8e8;
  }
  
  .input-box {
    border-radius: 20px;
    overflow: hidden;
    background: #fff;
    
    :deep(.el-input__inner) {
      border-radius: 20px;
      padding: 8px 20px;
      border: 1px solid #e8e8e8;
    }
    
    :deep(.el-input-group__append) {
      background: transparent;
      border: none;
      box-shadow: none;
    }
  }
  
  .send-btn {
    border-radius: 16px;
    padding: 8px 24px;
    font-weight: 500;
    transition: all 0.2s ease;
    
    &:hover {
      transform: translateY(-1px);
    }
  }
  
  @media (max-width: 768px) {
    .chat-container {
      height: 100vh;
    }
    
    .message-wrap {
      max-width: 85%;
    }
    
    .avatar {
      width: 32px;
      height: 32px;
    }
  }
  </style>